<?php

namespace App\V3\V3_2_7\Controllers;

use App\Http\Requests\V3_2_7\SetShelfLocationRequest;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use App\V3\V3_2_7\Services\ShelfService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 货架管理
 * AUTHOR  : zl
 * DateTime: 2022/08/22
 */
class ShelfController extends BaseController
{
    /**
     * 通过仓库获取货架及库位
     */
    public function GetShelf(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storageId' => 'required|integer',//仓库ID
        ], [
            'storageId.required' => '参数`storageId`缺失',
            'storageId.integer' => '参数`storageId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        return $this->success(
            ShelfService::get_list_by_main_id($this->getMainUserId(), $data)
        );
    }

    /**
     * 添加货架
     */
    public function ShelfCreate(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'shelfName' => 'required|string',//货架名称
            'storageId' => 'required|integer',//仓库ID
        ], [
            'shelfName.required' => '参数`shelfName`缺失',
            'shelfName.string' => '参数`shelfName`仅能为字符串',
            'storageId.required' => '参数`storageId`缺失',
            'storageId.integer' => '参数`storageId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

//        if(empty(ShelfService::is_use_shelf($this->getMainUserId()))){
//            return $this->fail('','未开启货架功能');
//        }

        $shelf = new StorageShelfModel;
        $shelf->shelf_name = $request->shelfName;
        $shelf->main_id = $this->getMainUserId();
        $shelf->storage_id = $request->storageId;
        $shelf->shelf_type = StorageShelfModel::CREATETYPE;
        $shelf->remark = empty($data['remark']) ? '' : $data['remark'];
        $shelf->sort = empty($data['sort']) ? 0 : $data['sort'];

        $res = $shelf->save();
        if ($res) {
            $this->log('添加货架', $data, '货架名称:' . $shelf->shelf_name . ',创建成功!');
            return $this->success('', '添加成功');
        } else {
            return $this->fail('', '添加失败');
        }
    }

    /**
     * 添加货架
     */
    public function ShelfUpdate(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'shelfName' => 'required|string',//货架名称
//            'storageId' =>'required|integer',//仓库ID
            'shelfId' => 'required|integer',//货架ID
        ], [
            'shelfName.required' => '参数`shelfName`缺失',
            'shelfName.string' => '参数`shelfName`仅能为字符串',
//            'storageId.required' => '参数`storageId`缺失',
//            'storageId.integer' => '参数`storageId`仅能为数字',
            'shelfId.required' => '参数`shelfId`缺失',
            'shelfId.integer' => '参数`shelfId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['remark'] = empty($data['remark']) ? '' : $data['remark'];
        $data['sort'] = empty($data['sort']) ? '' : $data['sort'];

//        if(empty(ShelfService::is_use_shelf($this->getMainUserId()))){
//            return $this->fail('','未开启货架功能');
//        }

        $info = StorageShelfModel::where('id', $data['shelfId'])
            ->where('main_id', $this->getMainUserId())
            ->where('status', StorageShelfModel::USEDSTATUS)->first();
        /* if($info['shelf_type'] == StorageShelfModel::DEFAULTTYPE){
             return $this->fail('','默认货架不允许修改');
         }*/
        if (empty($info)) {
            return $this->fail('', '无货架信息！');
        }
        if (StorageShelfModel::query()->where([
            'status' => 1,
            'main_id' => $this->getMainUserId(),
            'shelf_name' => $data['shelfName'],
            ['id', '!=', $info['id']],
            'storage_id' => $info['storage_id']
        ])->exists()) {
            return $this->fail('', '同仓库下，货架名称不能重复！');
        }
        $res = StorageShelfModel::where('id', $data['shelfId'])
            ->where('main_id', $this->getMainUserId())
            ->where('status', StorageShelfModel::USEDSTATUS)
            ->update([
                'shelf_name' => $data['shelfName'],
                'remark' => $data['remark'],
                'sort' => $data['sort']
            ]);

        if ($res) {
            $this->log('修改货架', $data, '货架名称:' . $data['shelfName'] . ',信息已更改!');
            return $this->success('', '修改成功');
        } else {
            return $this->fail('', '修改失败');
        }

    }

    public function ShelfDel(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'shelfId' => 'required|integer',//货架ID
        ], [
            'shelfId.required' => '参数`shelfId`缺失',
            'shelfId.integer' => '参数`shelfId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

//        if(empty(ShelfService::is_use_shelf($this->getMainUserId()))){
//            return $this->fail('','未开启货架功能');
//        }

        $shelf_info = StorageShelfModel::where('id', $data['shelfId'])->first();

        if ($shelf_info['shelf_type'] == StorageShelfModel::DEFAULTTYPE) {
            return $this->fail('', '默认货架不能删除');
        }

        $judging_status = ShelfService::judging_del($data['shelfId'], 2, $this->getMainUserId());

        if (!empty($judging_status)) {
            $res = StorageShelfModel::where('id', $data['shelfId'])
                ->where('main_id', $this->getMainUserId())
                ->where('status', StorageShelfModel::USEDSTATUS)
                ->update(['status' => StorageShelfModel::DELETESTATUS]);
            if ($res) {
                $this->log('删除货架', $data, '货架名称:' . $shelf_info['shelf_name'] . ',已删除!');
                return $this->success('', '删除成功');
            } else {
                return $this->fail('', '删除失败');
            }
        } else {
            return $this->fail('', '此货架还有库存商品，不能删除');
        }

    }


    public function ShelfList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storageId' => 'required|integer',//仓库ID
        ], [
            'storageId.required' => '参数`storageId`缺失',
            'storageId.integer' => '参数`storageId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        return $this->success(
            ShelfService::shelf_list($this->getMainUserId(), $data)
        );
    }

    /**
     * 货架详情
     */
    public function ShelfInfo(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'shelfId' => 'required|integer',//货架ID
        ], [
            'shelfId.required' => '参数`shelfId`缺失',
            'shelfId.integer' => '参数`shelfId`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $info = StorageShelfModel::where('id', $data['shelfId'])
            ->where('main_id', $this->getMainUserId())
            ->where('status', StorageShelfModel::USEDSTATUS)->first();

        if (empty($info)) {
            return $this->fail('', '没查询到相关数据');
        }

        $storage = StorageModel::where(['id' => $info['storage_id']])->first();

        $res = [];
        $res['storage_name'] = $storage['storage_name'];
        $res['storage_id'] = $storage['id'];
        $res['shelf_id'] = $info['id'];
        $res['shelf_name'] = $info['shelf_name'];
        $res['remark'] = $info['remark'];
        $res['sort'] = $info['sort'];
        $res['total_standard_num'] = StorageShelfLocationModel::query()
            ->where([
                'status' => 1,
                'shelf_id' => $info['id']
            ])->sum("standard_num") ?? 0;
        $res['total_num'] = StorageManageModel::query()
            ->where([
                'storage_id' => $storage['id'],
                'shelf_id' => $info['id'],
                'delete_flag' => 0,
                'main_id' => $this->getMainUserId()
            ])->sum('in_storage_num');
        return $this->success($res, '获取成功');
    }

    /**
     *设置默认货架与库位
     * Author: zlf
     * Created at 2024/8/10 16:52
     * @param SetShelfLocationRequest $request
     * @return JsonResponse
     */
    public function setDefaultShelfLocation(SetShelfLocationRequest $request): JsonResponse
    {
        $data = $request->all();
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->operateLog('设置默认货架与库位', $data, $data['time']);
        return ShelfService::setDefaultShelfLocation($data);
    }
}
